$.ajax({
  url: "./static/boxy/toolbox/toolbox.xml",
  type: "get",
  async: true,
  dataType: "xml",
  success: function (data) {
    let xmlDoc = $(data).find("toolbox").html();
    $("#toolbox").html(xmlDoc);
    localStorage.setItem("toolbox", xmlDoc);
    loadWorkspace();
  },
  error: function (jqXHR, textStatus, errorThrown) {
    $("#toolbox").html(localStorage.getItem("toolbox") || "");
    console.error("Boxy Error: An unknown error occurred in toolbox.");
    console.error("Boxy is loading the data from the storage instead.");
    console.error("Please check your settings and try again.");
    console.error(jqXHR);
    console.error("ErrorType:", textStatus);
    console.error(errorThrown);
    loadWorkspace();
  },
});

var workspace;

function loadWorkspace() {
  // 工作区注入
  var blocklyArea = document.getElementById("blocklyArea");
  var blocklyDiv = document.getElementById("blocklyDiv");
  workspace = Blockly.inject("blocklyDiv", {
    toolbox: document.getElementById("toolbox"),
    plugins: {
      blockDragger: ScrollBlockDragger,
      metricsManager: ScrollMetricsManager,
    },
    trashcan: false,
    media:'./media/',
    zoom: {
      controls: true,
      wheel: true,
      startScale: 0.8,
      maxScale: 1.6,
      minScale: 0.4,
      scaleSpeed: 1.5,
    },
    move: {
      scrollbars: true,
      drag: true,
      wheel: true,
    },
    theme: "zelos",
    renderer: "zelos",
  });

  const pluginWorkspaceSearch = new WorkspaceSearch(workspace);
  pluginWorkspaceSearch.init();
  const pluginScrollOptions = new ScrollOptions(workspace);
  pluginScrollOptions.init();

  var onresize = function (e) {
    let element = blocklyArea;
    let x = 0;
    let y = 0;
    do {
      x += element.offsetLeft;
      y += element.offsetTop;
      element = element.offsetParent;
    } while (element);
    blocklyDiv.style.left = x + "px";
    blocklyDiv.style.top = '70' + "px";
    Blockly.svgResize(workspace);
  };
  window.addEventListener("resize", onresize, false);
  onresize();
  Blockly.svgResize(workspace);
}
